//
//  RegisteredViewController.m
//  CBT
//
//  Created by Mr.Zhang on 2018/11/23.
//  Copyright © 2018 Mr.Zhang. All rights reserved.
//

#import "RegisteredViewController.h"
#import "EmailRegisteredViewController.h"

#import "RegisteredViewModel.h"

@interface RegisteredViewController ()<UITextFieldDelegate>

@property (nonatomic,strong) id timer;

@property (nonatomic, strong) RegisteredViewModel *viewModel;

@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;
@property (weak, nonatomic) IBOutlet UITextField *invitationTextField;
@property (weak, nonatomic) IBOutlet UIView *invitationLineView;

@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *codeButton;
@property (weak, nonatomic) IBOutlet UIButton *cityCodeBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UIButton *emailRegisterBtn;

@property (weak, nonatomic) IBOutlet UILabel *hasIDLabel;
@property (weak, nonatomic) IBOutlet UILabel *cityCodeLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *phoneTopTextFieldCon;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *cityCodeTopCon;

@end

@implementation RegisteredViewController

#pragma mark - VC Life
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.showType == 1) {
        self.emailRegisterBtn.hidden    = YES;
        self.invitationTextField.hidden = YES;
        self.invitationLineView.hidden  = YES;
    }
    
    [self showInfoMsg];
    [self inputAction];
    [self outPutAction];
}

-(void)dealloc {
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
}

- (void)showInfoMsg {
    self.fd_prefersNavigationBarHidden = YES;

    if (self.showType == 1) {
        self.hasIDLabel.hidden = YES;
        self.loginBtn.hidden   = YES;
    }
    
    [_codeButton setTitle:kLocalizedString(@"发送验证码", nil) forState:(UIControlStateNormal)];
    _phoneTextField.placeholder = kLocalizedString(@"请输入您的手机号码", nil);
    _codeTextField.placeholder  = kLocalizedString(@"请输入验证码", nil);
    _pwdTextField.placeholder   = kLocalizedString(@"请输入8-20位密码", nil);
    _invitationTextField.placeholder = kLocalizedString(@"请输入邀请码", nil);
    [_registerBtn setTitle:kLocalizedString(self.showType == 0 ? @"注册" : @"确定", nil) forState:(UIControlStateNormal)];
    _registerBtn.backgroundColor = UIColorFromRGB(0xff5101);
    [_emailRegisterBtn setTitle:kLocalizedString(self.showType == 0 ? @"邮箱注册" : @"邮箱找回", nil) forState:(UIControlStateNormal)];
    _hasIDLabel.text = kLocalizedString(@"已有账号?", nil);
    [_loginBtn setTitle:kLocalizedString(@"立即登录", nil) forState:(UIControlStateNormal)];
}

#pragma mark - sendCode
-(void)sendCodeActionWithBtn:(UIButton *)btn {
    __block NSInteger second = 60;
    //全局队列    默认优先级
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //定时器模式  事件源
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
    
    _timer = timer;
    
    //NSEC_PER_SEC是秒，＊1是每秒
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), NSEC_PER_SEC * 1, 0);
    //设置响应dispatch源事件的block，在dispatch源指定的队列上运行
    dispatch_source_set_event_handler(timer, ^{
        //回调主线程，在主线程中操作UI
        dispatch_async(dispatch_get_main_queue(), ^{
            if (second > 0) {
                btn.userInteractionEnabled = NO;
                btn.backgroundColor = UIColorFromRGB(0xd3d8fd);
                [btn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
                btn.layer.borderWidth = 0;
                [btn setTitle:[NSString stringWithFormat:@"%lds",(long)second] forState:UIControlStateNormal];
                second--;
            }
            else {
                //这句话必须写否则会出问题
                btn.userInteractionEnabled = YES;
                btn.backgroundColor = [UIColor whiteColor];
                [btn setTitleColor:UIColorFromRGB(0x7889ff) forState:(UIControlStateNormal)];
                btn.layer.borderWidth = 1;
                dispatch_source_cancel(timer);
                [btn setTitle:@"发送验证码" forState:UIControlStateNormal];
            }
        });
    });
    //启动源
    dispatch_resume(timer);
}

#pragma mark - Input

-(void)inputAction {
    @weak(self)
    //点击注册
    [[_registerBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self_weak_.view endEditing:YES];
        [self_weak_ startClearBgColorLoading];
        NSString *area = self.cityCodeLabel.text;
        if ([area containsString:@"+"]) {
            area = [area substringFromIndex:1];
        }
        [[NSUserDefaults standardUserDefaults] setObject:area forKey:@"area"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        NSString *phone = self_weak_.phoneTextField.text;
        phone = [phone stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        [self_weak_.viewModel.registeredCommand execute:@{@"phone":phone,@"code":self_weak_.codeTextField.text,@"area":area,@"password":self_weak_.pwdTextField.text,@"avatar":self_weak_.invitationTextField.text,@"type":[NSString stringWithFormat:@"%ld",(long)self_weak_.showType]}];
    }];
    
    //选择城市代码
    [_cityCodeLabel bk_whenTapped:^{
        CBTCountryCodeViewController *vc = [[CBTCountryCodeViewController alloc]init];
        [vc setReturnCountryCodeBlock:^(NSString *countryName, NSString *code) {
            self_weak_.cityCodeLabel.text = [NSString stringWithFormat:@"%@",code];
        }];
        [self_weak_.navigationController pushViewController:vc animated:YES];
    }];
    
    [[_cityCodeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        CBTCountryCodeViewController *vc = [[CBTCountryCodeViewController alloc]init];
        [vc setReturnCountryCodeBlock:^(NSString *countryName, NSString *code) {
            self_weak_.cityCodeLabel.text = [NSString stringWithFormat:@"+%@",code];
        }];
        [self_weak_.navigationController pushViewController:vc animated:YES];
    }];
    
    //邮箱注册
    [[_emailRegisterBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        EmailRegisteredViewController *emailVC = [story instantiateViewControllerWithIdentifier:@"emailRegisteredVC"];
        emailVC.showType = self_weak_.showType;
        [self_weak_.navigationController pushViewController:emailVC animated:YES];
    }];
    
    //发送验证码
    [[_codeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self_weak_ startClearBgColorLoading];
        [self_weak_.view endEditing:YES];
        NSString *countryCode = self.cityCodeLabel.text;
        if ([countryCode containsString:@"+"]) {
            countryCode = [countryCode substringFromIndex:1];
        }
        [self_weak_.viewModel.sendCodeCommand execute:@{@"phone":self_weak_.phoneTextField.text,@"code":countryCode,@"type": self_weak_.showType == 0 ? @"1" : @"2"}];
    }];
    
    //立即登录
    [[_loginBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self_weak_.navigationController popToRootViewControllerAnimated:YES];
    }];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSMutableString *s = [NSMutableString stringWithFormat:@"%@",textField.text];
    [s insertString:string atIndex:range.location];
    if ([NSString isBlankString:string]) {
        return YES;
    }
    if (([NSString isContainsEmoji:string] && ![NSString isNineKeyBoard:string]) || (string.isEmoji && ![NSString isNineKeyBoard:string]) || (([NSString hasEmoji:string] && ![NSString isNineKeyBoard:string]))) {
        return NO;
    }
    if (![NSString validateNumber:string] && textField.tag == 100) {
        return NO;
    }
    
    return YES;
}

#pragma mark - OutPut
-(void)outPutAction {
    @weak(self)
    //注册成功
    [self.viewModel.registeredCommand.executionSignals.switchToLatest subscribeNext:^(id  _Nullable x) {
        [self_weak_ stopLoading];
        if (self_weak_.showType == 1) {
            [self_weak_.navigationController popToRootViewControllerAnimated:YES];
        }
        else {
            [self_weak_.navigationController popToRootViewControllerAnimated:NO];
            [((AppDelegate*)[UIApplication sharedApplication].delegate) changeRootVC];
            [[NSUserDefaults standardUserDefaults] setValue:self_weak_.phoneTextField.text forKey:@"phoneNumber"];
            [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"emailAddress"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }];
    
    [self.viewModel.registeredCommand.errors subscribeNext:^(NSError * _Nullable x) {
        [self_weak_ stopLoading];
    }];
    
    //发送验证码成功
    [self.viewModel.sendCodeCommand .executionSignals.switchToLatest subscribeNext:^(id  _Nullable x) {
        [self_weak_ stopLoading];
        [self_weak_ sendCodeActionWithBtn:self_weak_.codeButton];
    }];
    
    [self.viewModel.sendCodeCommand.errors subscribeNext:^(NSError * _Nullable x) {
        [self_weak_ stopLoading];
    }];
}

#pragma mark - Lazy

- (RegisteredViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [[RegisteredViewModel alloc]init];
    }
    return _viewModel;
}


@end
